import datetime

from django.contrib import admin
from .models import Device, Data, Datapack


# Register your models here.


class DataTimeFilter(admin.SimpleListFilter):
	title = 'time'
	parameter_name = 'time'

	options = (
		(30 * 60, 'in 30 minutes'),
		(60 * 60, 'in 1 hour'),
		(60 * 60 * 2, 'in 2 hours'),
		(86400, 'in 1 day'),
		(86400 * 3, 'in 3 days'),
		(86400 * 7, 'in 1 week'),
		(86400 * 7 * 14, 'in 2 weeks'),
		(86400 * 30, 'in 30 days'),
	)

	def lookups(self, request, model_admin):
		return self.options

	def queryset(self, request, queryset):
		if self.value() is None:
			return queryset

		for option in self.options:
			if int(self.value()) == option[0]:
				return queryset.filter(
					time__gte=datetime.datetime.now() - datetime.timedelta(seconds=option[0])
				)


class DeviceAdmin(admin.ModelAdmin):
	list_display = ('name', 'is_online', 'device_number', 'last_active_time')
	list_filter = ['is_online']


class DataAdmin(admin.ModelAdmin):
	list_display = ('name', 'value', 'unit', 'time', 'device')
	list_filter = [DataTimeFilter, 'device', 'name']
	search_fields = ['device']


class DatapackAdmin(admin.ModelAdmin):
	list_display = ('device', 'time', 'hash')
	list_filter = ['device', DataTimeFilter]


admin.site.register(Device, DeviceAdmin)
admin.site.register(Data, DataAdmin)
admin.site.register(Datapack, DatapackAdmin)
